const headContainer = document.querySelector('.header-area')
const footerContainer = document.querySelector('.footer-wrapper')
const cartOpenBtn = document.querySelector('.minicart-btn')
const cartCloseBtn = document.querySelector('.minicart-close')
const cartListEle = document.querySelector('.minicart-item-wrapper ul')
const totalPriceEle = document.getElementById('total-price')
const totalQuantityEle = document.getElementById('total-quantity')

const cartList = [
    {
        "iid": "1m70y5k",
        "price": "59.00",
        "quantity": 2,
        "img": "http://s11.mogucdn.com/mlcdn/c45406/180808_600abce0g8dc8i4f6ic7k27i7837l_640x960.jpg_320x999.jpg",
        "title": "2018秋季新款韩版百搭格子长袖衬衫+前短后长针织气质开衫外套+高腰直筒九分牛仔裤三件套装",
    },
    {
        "iid": "1jw0sr2",
        "price": "56.64",
        "quantity": 1,
        "img": "http://s11.mogucdn.com/p2/170301/106341701_4kfgdd3001475k8h1l365al2k5ed6_640x960.jpg_320x999.jpg",
        "title": "2018 新款女装上衣文艺棉麻短袖t恤 V领衫T恤女短袖女T桖",
    },
]

class Cart {
    constructor(cartList = []) {
        this.cartList = cartList
        this.defineProperties()
        this.updateCartDOM()
        
    }
    
    defineProperties(){
        Object.defineProperties(this, {
            totalPrice: {
                get() {
                    return this.cartList.reduce((accumulator, item) => accumulator + item.price * item.quantity, 0)
                }
            },
            totalQuantity: {
                get() {
                    return this.cartList.reduce((accumulator, item) => accumulator + item.quantity, 0)
                }
            }
        })
    }

    showCart() {
        document.body.classList.add('fix');
        document.querySelector(".minicart-inner").classList.add('show')
    }

    closeCart() {
        document.body.classList.remove('fix')
        document.querySelector(".minicart-inner").classList.remove('show')
    }

    addToCart(goods) {
        let cartGoods = this.cartList.find(item => item.iid === goods.iid)
        if (cartGoods) {
            cartGoods.quantity++
        } else {
            cartGoods = this.toCartGoods(goods)
            this.cartList.push(cartGoods)
        }
        this.updateCartDOM()
    }

    toCartGoods(goods) {
        return {
            "iid": goods.iid,
            "price": goods.price,
            "quantity": 1,
            "img": goods.show.img,
            "title": goods.title,
        }
    }

    deleteFromCart(iid) {
        for (let index in this.cartList) {
            const cartGoods = this.cartList[index]
            if (cartGoods.iid === iid) {
                this.cartList.splice(index, 1)
                break
            }
        }
        this.updateCartDOM()
    }

    updateCartDOM() {
        const cartListHtmlArr = this.cartList.map(item => {
            const html = `
            <li class="minicart-item">
                <div class="minicart-thumb">
                    <a href="#">
                        <img src="${item.img}" alt="product">
                    </a>
                </div>
                <div class="minicart-content">
                    <h3 class="product-name">
                        <a href="product-details.html">${item.title}</a>
                    </h3>
                    <p>
                        <span class="cart-quantity">${item.quantity} <strong>&times;</strong></span>
                        <span class="cart-price">￥${item.price}</span>
                    </p>
                </div>
                <button class="minicart-remove" data-iid="${item.iid}">
                    <i class="lnr lnr-cross" data-iid="${item.iid}"></i>
                </button>
            </li>`
            return html
        })
        const cartListHtmlStr = cartListHtmlArr.join('')
        cartListEle.innerHTML = cartListHtmlStr

        totalPriceEle.innerText = "￥" + this.totalPrice.toFixed(2)
        totalQuantityEle.innerText = this.totalQuantity

        if(cartOpenBtn){
            cartOpenBtn.querySelector('.notification').innerText = this.totalQuantity
        }
    }

}

const cart = new Cart(cartList)

/**
 * 把html字符串转换成DOM对象，html片段只有一个根节点
 * @param {str} html 
 */
function htmlToElement(html) {
    const wrapper = document.createElement('div')
    wrapper.innerHTML = html
    return wrapper.firstElementChild
}

function getHeader() {
    ajax({
        url: "./header.html",
        success: function (data, statusText, xhr) {
            const htmlStr = xhr.responseText
            headContainer.innerHTML = htmlStr
        },
    })
}

function getFooter() {
    ajax({
        url: "./footer.html",
        success: function (data, statusText, xhr) {
            const htmlStr = xhr.responseText
            footerContainer.innerHTML = htmlStr
        },
    })
}

function getMiniCart() {
    ajax({
        url: "./mini-cart.html",
        success: function (data, statusText, xhr) {
            const htmlStr = xhr.responseText
            const miniCartElement = htmlToElement(htmlStr)
            document.body.append(miniCartElement)
        },
    })
}

// getHeader()
getFooter()
getMiniCart()



cartOpenBtn.onclick = function (e) {
    e.preventDefault()
    cart.showCart()
} 
cartCloseBtn.onclick = function(e) {
    e.preventDefault()
    cart.closeCart()
} 






cartListEle.addEventListener("click", function (e) {
    const target = e.target
    if (target.className === "minicart-remove" || target.classList.contains("lnr-cross")) {
        const iid = target.dataset.iid
        cart.deleteFromCart(iid)
    }
})


/**
 * 
 * @param {Object} element 
 * @param {str} 选择器
 */
function findParent(element, selector) {
    if (element === document) {
        return document
    }
    const parentElement = element.parentElement
    if (!selector) {
        return parentElement
    }
    const elements = [...document.querySelectorAll(selector)]
    if (elements.includes(parentElement)) {
        return parentElement
    } else {
        return findParent(parentElement, selector)
    }

}
